#pragma once
#include <iostream>
#include <string>
// #include "Log.hpp"
#include <error.h>
#include <string.h>
#include "nocopy.hpp"
#include "Comm.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include "thread.hpp"
#include "Lockguard.hpp"
#include "Task.hpp"
#include <functional>
#include <unordered_map>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

// Log lg;

const static int default_backlog = 5; // TODO

using task_t = function<void(void)>;
using callback_t = function<void(int, InetAddr &)>; // 可能会调整参数类型


class TcpServer : public nocopy // 用于1不想让服务器被拷贝
{
public:
    TcpServer(uint16_t port)
        : _port(port), _isrunning(false)
    {
    }
    void Init()
    {
        // 1.创建套接字
        // sockfd本质就是文件描述符
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sock < 0)
        {
            lg.LogMessage(Fatal, "create socket error,errno code:%, error string:%s\n", errno, strerror(errno));
            exit(Socket_Err);
        }
        lg.LogMessage(Debug, "create socket success,sockfd:%d\n", _listen_sock);

        // 固定写法，解决一些少量的bind失败的问题
        int optval = 1;
        setsockopt(_listen_sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &optval, sizeof(optval));

        // 2.绑定套接字地址信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // INADDR_ANY的值为0，表示绑定到所有可用的网络接口

        // bind
        int n = ::bind(_listen_sock, (struct sockaddr *)&local, sizeof(local)); // 将套接字地址结构体绑定到套接字
        if (n != 0)
        {
            lg.LogMessage(Fatal, "bind err ,%d:%s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
        lg.LogMessage(Debug, "bind success\n");

        // 3.设置socket为监听状态，tcp特有的
        int m = listen(_listen_sock, default_backlog);
        if (m != 0)
        {
            lg.LogMessage(Fatal, "listen err ,%d:%s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
        lg.LogMessage(Debug, "listen successs,sockfd:%d\n", _listen_sock);

        ThreadNs::ThreadPool<task_t>::Getinstance()->Start();

        _funcs.insert(make_pair("defaultservice",bind(&TcpServer::Defaultserverice,this,placeholders::_1,placeholders::_2)));
    }

    // TCP连接服务，是全双工通信的
    void serverice(int sockfd, InetAddr addr)
    {
        char buffer[1024];
        while (true)
        {
            size_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                // cout << "client say#  " << buffer << endl;
                cout << addr.PrintDebug() << "$" << buffer << endl;

                string echo_string = "server say#";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0) // read如果返回值是0，表示读到了文件的结尾（对端关闭了）
            {
                lg.LogMessage(Info, "client close the connection\n");
                break;
            }
            else
            {
                lg.LogMessage(Error, "read socket error,errno code:%d,error string:%s\n", errno, strerror(errno));
                break;
            }
        }
    }


    void Start()
    {
        _isrunning = true;
        //signal(SIGCHLD, SIG_IGN); // 忽略子进程结束信号,让子进程自己释放自己的资源
        while (_isrunning)
        {
            // 4.获取用户连接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listen_sock, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                lg.LogMessage(Warning, "accept socket error,errno code:%d,error string:%s\n", errno, strerror(errno));
                continue;
            }
            lg.LogMessage(Debug, "accept a new client,sockfd:%d\n", sockfd);

            // 5.提供服务
            // 线程池
            InetAddr addr(peer);
            task_t t = bind(&TcpServer::Routine, this, sockfd, addr);
            ThreadNs::ThreadPool<task_t>::Getinstance()->Push(t);
        }
    }

    string Read(int sockfd)
    {
        char type[1024];
        size_t n = read(sockfd, type, sizeof(type) - 1);
        if (n > 0)
        {
            type[n] = 0;
           
        }
        else if (n == 0) // read如果返回值是0，表示读到了文件的结尾（对端关闭了）
        {
            lg.LogMessage(Info, "client close the connection\n");
        }
        else
        {
            lg.LogMessage(Error, "read socket error,errno code:%d,error string:%s\n", errno, strerror(errno));
        }
        return type;
    }

    void Routine(int sockfd, InetAddr addr)
    {
        _funcs["defaultservice"](sockfd, addr);

        string type=Read(sockfd);
        lg.LogMessage(Debug,"%s select %s\n",addr.PrintDebug().c_str(),type.c_str());
        if(type=="ping")
            _funcs[type](sockfd,addr);//??
        else if(type=="translate")
            _funcs[type](sockfd,addr);//??
        else if(type=="transform")
            _funcs[type](sockfd,addr);//??
        // else
        //      _funcs["default"](sockfd,addr);//??
        else
            {}

        close(sockfd);
    }
    void Defaultserverice(int sockfd,InetAddr& addr)
    {
        string serverice_list="|";
        for(auto func:_funcs)
        {
            serverice_list+=func.first+"|";
        }
        write(sockfd,serverice_list.c_str(),serverice_list.size());
    }
    void RegisterFunc(string name, callback_t func)
    {
        _funcs[name] = func;
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listen_sock; // 这个套接字主要用于监听
    // 不是用于和client进行通信的
    bool _isrunning;

    // 构建业务逻辑
    unordered_map<string, callback_t> _funcs;
};